package com.qianfeng.shopping.dao;

import com.qianfeng.shopping.util.ConnDb;
import com.qianfeng.shopping.util.GetUuid;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

public abstract class BaseDao {
    // 查询多个存到Map
    public <T> Map<String,T> selectAll(String sql,Object[] arr){
        Map<String,T> map = new HashMap<>();
        Connection conn = ConnDb.getConnection();
        PreparedStatement pst = null;
        ResultSet rs = null;
        try {
            pst = conn.prepareStatement(sql);
            //对占位符赋值
            for (int i = 0; i < arr.length; i++) {
                pst.setObject(i+1,arr[i]);
            }
            rs = pst.executeQuery();
            while(rs.next()){
                // 收集数据
                T t = this.rowMapper(rs);
                map.put(GetUuid.getUuid(),t);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            ConnDb.closeDb(rs,pst,conn);
        }
        return  map;
    }
    // 查询单个
    public <T>T select(String sql,Object[] arr){
        T t = null;
        Connection conn = ConnDb.getConnection();
        PreparedStatement pst = null;
        ResultSet rs = null;
        try {
            pst = conn.prepareStatement(sql);
            //对占位符赋值
            for (int i = 0; i < arr.length; i++) {
                pst.setObject(i+1,arr[i]);
            }
            rs = pst.executeQuery();
            if(rs.next()){
                // 收集数据
                t = this.rowMapper(rs);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            ConnDb.closeDb(rs,pst,conn);
        }
        return  t;
    }
    //  定义抽象方法  参数是结果集  然后必须重写该方法 实现数据的收集
    public abstract  <T>T  rowMapper(ResultSet rs);
    // 共通的增删改方法
//    public boolean update(String sql,Object... arr ){
    public boolean update(String sql,Object[]  arr ){
        Connection conn = ConnDb.getConnection();
        PreparedStatement pst = null;
        try {
            pst = conn.prepareStatement(sql);
            //对占位符赋值
            for (int i = 0; i < arr.length; i++) {
                pst.setObject(i+1,arr[i]);
            }
            return pst.executeUpdate()==1;
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            ConnDb.closeDb(null,pst,conn);
        }
        return false;
    }
}
